package com.ksc.wordcount.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

public class UrlTopNConfListener {

    private static String projectPath = System.getProperty("user.dir");
    private static String fileSeparator = System.getProperty("file.separator");

    private static long lastCallbackTime = 0; // 记录上一次执行回调函数的时间戳

    public static void start(Consumer<Map<String, String>> callback) {
        String urltopnPath = projectPath + fileSeparator + "thriftTask.conf";

        try {
            Path filePath = Paths.get(urltopnPath);
            WatchService watchService = FileSystems.getDefault().newWatchService();
            filePath.getParent().register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

            System.out.println("Listening to changes in thriftTask.conf...");

            Thread thread = new Thread(() -> {
                while (true) {
                    try {
                        WatchKey key = watchService.take();

                        for (WatchEvent<?> event : key.pollEvents()) {
                            if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                                long currentTime = System.currentTimeMillis();
                                if (currentTime - lastCallbackTime > 1000) { // 设置一个时间间隔，例如1秒
                                    lastCallbackTime = currentTime;

                                    Path modifiedFile = (Path) event.context();
                                    if (modifiedFile.getFileName().toString().equals("thriftTask.conf")) {
                                        System.out.println("thriftTask.conf has been modified. Reloading lasted properties...");

                                        Map<String, String> urltopnProperty = getUrltopnProperties(urltopnPath);
                                        callback.accept(urltopnProperty);
                                    }
                                }
                            }
                        }

                        key.reset();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });

            thread.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, String> getUrltopnProperties(String urltopnPath) {
        // 获取最新配置
        Map<String, String> property = new HashMap<>();

        try (BufferedReader br = new BufferedReader(new FileReader(urltopnPath))) {
            String line;
            String lastLine = null;

            // 读取整个文件并记录最后一行
            while ((line = br.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    lastLine = line;
                }
            }

            if (lastLine != null) {
                String[] fields = lastLine.split("\\s+");

                if (fields.length >= 6) {
                    String applicationId = fields[0];
                    String inputPath = fields[1];
                    String outputPath = fields[2];
                    String topN = fields[3];
                    String reduceTask = fields[4];
                    String splitSize = fields[5];

                    property.put("applicationId", applicationId);
                    property.put("inputPath", inputPath);
                    property.put("outputPath", outputPath);
                    property.put("topN", topN);
                    property.put("reduceTask", reduceTask);
                    property.put("splitSize", splitSize);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return property;
    }

//    public static void main(String[] args) {
//        Map<String, String> urltopnProperty = PropertyUtil.getUrltopnProperties();
//
//        AtomicReference<String> inputPath = new AtomicReference<>(urltopnProperty.get("inputPath"));
//        AtomicReference<String> outputPath = new AtomicReference<>(urltopnProperty.get("outputPath"));
//        AtomicReference<String> applicationId = new AtomicReference<>(urltopnProperty.get("applicationId"));
//        AtomicInteger reduceTaskNum = new AtomicInteger(Integer.parseInt(urltopnProperty.get("reduceTask")));
//        AtomicInteger TopN = new AtomicInteger(Integer.parseInt(urltopnProperty.get("topN")));
//        AtomicInteger splitSize = new AtomicInteger(Integer.parseInt(urltopnProperty.get("splitSize")));
//
//        Consumer<Map<String, String>> callback = (property) -> {
//            // 收到最新的配置，执行相应的操作
//            System.out.println("Received latest configuration:");
//            // 执行相应的操作
//            inputPath.set(property.get("inputPath"));
//            outputPath.set(property.get("outputPath"));
//            applicationId.set(property.get("applicationId"));
//            reduceTaskNum.set(Integer.parseInt(property.get("reduceTask")));
//            TopN.set(Integer.parseInt(property.get("topN")));
//            splitSize.set(Integer.parseInt(property.get("splitSize")));
//        };
//
//        UrlTopNConfListener.start(callback);
//
//        System.out.println(inputPath);
//        System.out.println(outputPath);
//        System.out.println(applicationId);
//        System.out.println(reduceTaskNum);
//        System.out.println(TopN);
//        System.out.println(splitSize);
//
//    }
}